<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <PageTools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总记录数：{{ total }}条</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right="{ row }">
              <el-button
                type="warning"
                size="small"
                @click="$router.push('/import')"
              >
                导入excel
              </el-button>
              <el-button
                v-if="canClick('p-em-import')"
                :loading="downloadLoading"
                type="danger"
                size="small"
                @click="exportData"
              >
                导出excel
              </el-button>
              <el-button
                v-if="canClick('p-em-add')"
                type="primary"
                size="small"
                @click="addpeople(row)"
              >
                新增员工
              </el-button>
            </template>
          </PageTools>
        </div>
        <div>
          <!-- table列表
          prop指定某一列数据作为排序列
          order升序ascending（小到大）descending（大到小）
          -->
          <el-table
            border
            :data="list"
            :default-sort="{ prop: 'workNumber', order: 'descending' }"
          >
            <el-table-column label="序号" type="index" />
            <el-table-column label="姓名" prop="username" />
            <el-table-column label="头像" prop="staffPhoto">
              <template #default="{ row }">
                <el-image
                  class="round"
                  :src="row.staffPhoto"
                  @click="showCode(row.staffPhoto)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="工号" prop="workNumber" />
            <el-table-column label="聘用形式">
              <!-- 用作用域插槽获取当前数据2. 格式化数据-->
              <template #default="{ row }">
                {{ formatForm(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="departmentName" />
            <el-table-column label="入职时间" sortable prop="correctionTime" />
            <el-table-column label="账户状态">
              <el-switch v-model="qy" />
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="$router.push(`/employees/detail/${row.id}`)"
                >
                  查看
                </el-button>
                <el-button type="text" size="small" @click="openload(row)">
                  分配角色
                </el-button>
                <el-button type="text" size="small" @click="delEip(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination
              background
              :current-page="param.page"
              :page-size="param.size"
              :page-sizes="[10, 5]"
              :total="total"
              layout="prev, pager, next, sizes"
              @current-change="changePage"
              @size-change="sizeChange"
            />
          </el-row>
        </div>
      </el-card>
    </div>
    <AddEmployee :show="show" @del-age="show = $event" />
    <!-- 显示二维码 -->
    <el-dialog
      title="头像二维码"
      :visible="showCodeDialog"
      width="30%"
      @close="close"
    >
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 分配角色 -->
    <AssignRole ref="userlogin" :show-role-dialog.sync="showRoleDialog" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EnumTypes from '@/api/constant/employees.js'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'

// 绘制二维码
import QrCode from 'qrcode'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data () {
    return {
      // 分配角色弹层
      showRoleDialog: false,
      // 弹层
      showCodeDialog: false,
      downloadLoading: false,
      show: false,
      // 根据封装的接口=》1.。拿到什么数据，2.需要传什么参数
      list: [],
      param: {
        page: 1,
        size: 10
      },
      total: 0,
      qy: true
    }
  },
  created () {
    this.getEmployeeList()
  },

  methods: {
    // 分配角色弹层
    openload (row) {
      // console.log('肉', row)
      this.showRoleDialog = true
      this.$refs.userlogin.getUserRoles(row.id)
    },
    // 关闭弹层
    close () {
      this.showCodeDialog = false
    },
    // 点击头像显示对应头像地址的二维码
    showCode (url) {
      if (!url) return
      this.showCodeDialog = true // dom数据的获取是异步的 需要用this.$nextTick()
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    async exportData () {
      // 开始导入
      this.downloadLoading = true
      // 准备需要导出的员工信息map映射关系
      const userMap = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      const header = Object.keys(userMap)
      const enHeader = Object.values(userMap)
      // console.log(header, enHeader)
      const data = this.transFormList(this.list, enHeader)
      // console.log(this.list, header, enHeader, data)
      // 把员工列表数据转换成二维数组[[],[]]
      // 根据映射关系获取
      const excel = await import('@/utils/Export2Excel')
      // console.log('导出方法', excel)
      excel.export_json_to_excel({
        // 表头 必填
        header,
        // 表头对应的具体数据 必填
        // data: [
        //   ['刘备', 100],
        //   ['关羽', 500]
        // ],
        data,
        filename: `elm-list-${Date.now()}`, // 导出下载的文件名称
        autoWidth: true, // 导出excel列宽度是否自适应
        bookType: 'xlsx' // 导出生成的文件类型
      })

      // 关闭导入
      this.downloadLoading = false
    },
    // 把LIST员工列表转成二维数组[[员工信息]，[员工信息]]
    transFormList (list, enHeader) {
      /**
 * 思路步骤：
 * 1.准备一个空数组
 */
      const secondArray = []
      list.forEach(user => {
        // 把user对象的值，放在一个数组中
        const itemArray = []
        for (const key in user) {
          if (enHeader.includes(key)) {
            // 处理聘用关系=>转换数字
            if (key === 'formOfEmployment') {
              itemArray.push(this.formatForm(user[key]))
            } else {
              itemArray.push(user[key])
            }
          }
        }
        secondArray.push(itemArray)
      })
      return secondArray
    },
    // 新增员工
    addpeople () {
      this.show = true
    },
    // 删除某个员工
    async delEip (row) {
      try {
        await this.$confirm(`确认删除${row.username}吗？`)
        await delEmployee(row.id)

        this.param.page = 1
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    }, // 格式化聘用形式：1：正式2.非正式
    formatForm (type) {
      console.log(EnumTypes.hireType)
      // 1. 根据数组生成映射关系（1：正式，2：非正式）2.根据映射关系获取value值
      const map = {}
      EnumTypes.hireType.forEach(item => {
        map[item.id] = item.value
      })
      // console.log('2数据', map)
      return map[type]
    },
    // 切换页面
    changePage (currpage) {
      this.param.page = currpage
      this.getEmployeeList()
    },
    sizeChange (currsize) {
      this.param.size = currsize
      this.getEmployeeList()
    },
    // 刷新列表
    async getEmployeeList () {
      const { total, rows } = await getEmployeeList(this.param)
      console.log('1数据', rows)
      this.list = rows
      this.total = total
    }
  }
}
</script>

<style lang="scss" scoped>
.round {
  border-radius: 80%;
}
</style>
